package com.weixing.mall.provider.support.excel.act;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.dto.SeckillOrderDto;
import com.weixing.mall.provider.api.model.dto.SeckillOrderImportDto;
import com.weixing.mall.provider.api.service.OrderServiceRpc;
import com.weixing.mall.provider.model.domain.Activity;
import com.weixing.mall.provider.model.domain.SeckillImport;
import com.weixing.mall.provider.service.ISeckillImportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;

/**
 * 秒杀活动订单导入处理类
 *
 * @author Small
 */
@Slf4j
public class SeckillOrderImportListener extends AnalysisEventListener<SeckillOrderImportCopyData> {

    public static final Integer ROLE_KEFU = 2;
    public static final Integer ROLE_AGENT = 1;


    /**
     * 活动
     */
    private Activity activity;

    /**
     * 订单服务
     */
    private OrderServiceRpc orderServiceRpc;

    private ISeckillImportService seckillImportService;

    private Integer role;

    private List<SeckillOrderImportCopyData> list = Lists.newArrayList();

    private List<SeckillOrderImportCopyData> importList = Lists.newArrayList();


    private static final int BATCH_SIZE = 1000;

    public SeckillOrderImportListener() {
    }


    public SeckillOrderImportListener(Activity activity, OrderServiceRpc orderServiceRpc, ISeckillImportService seckillImportService, Integer role) {
        this.activity = activity;
        this.orderServiceRpc = orderServiceRpc;
        this.seckillImportService = seckillImportService;
        this.role = role;
    }


    /**
     * 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
     *
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        throw exception;
    }

    @Override
    public void invoke(SeckillOrderImportCopyData seckillOrderImportData, AnalysisContext analysisContext) {
        log.info("解析到一条数据：{}", JSON.toJSONString(seckillOrderImportData));
        list.add(seckillOrderImportData);
        importList.add(seckillOrderImportData);
        if (list.size() >= BATCH_SIZE) {
            resolve();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        resolve();
        log.info("所有数据解析完毕");
        SysAuth sysExt = AuthUtil.getSysExt();
        // 记录导入记录
        int size = importList.size();
        List<SeckillImport> lists = Lists.newArrayList();
        SeckillImport seckillImport = null;
        for (int i = 0; i < size; i++) {
            SeckillOrderImportCopyData seckillOrderImportData = importList.get(i);
            seckillImport = new SeckillImport();
            seckillImport.setActId(activity.getId());
            seckillImport.setAgentSn(seckillOrderImportData.getAgentMobile());
            seckillImport.setOutTradeNo(seckillOrderImportData.getOutTradeNo());
            seckillImport.setIdentificationCode(seckillOrderImportData.getIdentificationCode());
            seckillImport.setProvince(seckillOrderImportData.getProvince());
            seckillImport.setCity(seckillOrderImportData.getCity());
            seckillImport.setRegion(seckillOrderImportData.getRegion());
            seckillImport.setAddrDetail(seckillOrderImportData.getAddrDetail());
            seckillImport.setContactUser(seckillOrderImportData.getContactUser());
            seckillImport.setContactPhone(seckillOrderImportData.getContactPhone());
            seckillImport.setCreator(sysExt.getRealName());
            seckillImport.setCreatorId(sysExt.getUid());
            seckillImport.setBindType(role);
            lists.add(seckillImport);
        }
        seckillImportService.saveBatch(lists, 500);
    }


    private void resolve() {
        List<SeckillOrderImportDto> dtoList = Lists.newArrayList();
        SeckillOrderImportDto dto = null;
        for (SeckillOrderImportCopyData data : list) {
            dto = new SeckillOrderImportDto();
            BeanUtils.copyProperties(data, dto);
            dtoList.add(dto);
        }
        SeckillOrderDto orderDto = new SeckillOrderDto();
        orderDto.setOrderList(dtoList);
        orderDto.setRebateRule(activity.getRebateRule());
        orderDto.setActId(activity.getId());
        Result result = null;
        if (ROLE_AGENT.equals(role)) {
            result = orderServiceRpc.executeSeckillOrderImport(orderDto);
        } else {
            result = orderServiceRpc.executeSeckillOrderImport4kefu(orderDto);
        }
        if (!result.isSuccess()) {
            throw new BusinessException(result.getMsg());
        }
    }
}
